#!/bin/bash

# Provide source directive to shellcheck.
# shellcheck source=meta-facebook/meta-greatlakes/recipes-phosphor/state/phosphor-state-manager/power-cmd
source /usr/libexec/phosphor-state-manager/power-cmd

CHASSIS_ID=$1
SLOT=$(( $1-1 ))
OFFSET=$(( 0x9 + SLOT ))

# Server 12v power off
chassis-power-off()
{
        result=$(i2cset -y "$CPLD_BUS_NUM" "$CPLD_PWR_CTRL_ADDR" "$OFFSET" "$POW_OFF_SLOT")
        echo "$result"
        sleep 1

        # Check chassis status after doing 12V off
        chassis_status=$(chassis-power-status $SLOT)
        if [ "$chassis_status" == "$STATE_OFF" ]
        then
                busctl set-property "$CHASSIS_BUS_NAME""$CHASSIS_ID" "$CHASSIS_OBJ_PATH""$CHASSIS_ID" "$CHASSIS_INTF_NAME" "$CHASSIS_PROPERTY_NAME" s "$CHASSIS_OFF"
                echo "Chassis is power off"
        else
                busctl set-property "$CHASSIS_BUS_NAME""$CHASSIS_ID" "$CHASSIS_OBJ_PATH""$CHASSIS_ID" "$CHASSIS_INTF_NAME" "$CHASSIS_PROPERTY_NAME" s "$CHASSIS_ON"
                echo "Chassis is power on"
                exit 0;
        fi
}

chassis_status=$(chassis-power-status $SLOT)
if [ "$chassis_status" == "$STATE_UNKNOWN" ]
then
        echo "Invalid slot id"
        exit 1;
elif [ "$chassis_status" == "$STATE_ON" ]
then
        chassis-power-off
        exit 0;
else
        echo "Chassis is already off"
        exit 0;
fi
